package com.heima.wemedia.filter;

import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 从请求体获得用户信息，设置到线程变量ThredLoacd中，
 * 以方便本线程随时可以取值
 *
 * 注意：请求中的用户信息只保存在请求体中，请求结束就没有，
 * 线程变量中所以需要取出放入
 */
@Log4j2
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
@Order(1)
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response= (HttpServletResponse)servletResponse;
        //获取请求头中的userId
        String userId = request.getHeader("userId");
        //存入到线程变量中
        if (userId!=null&&userId.length()>0){
            WmUser wmUser=new WmUser();
            wmUser.setId(Integer.parseInt(userId));
            //  WmUser wmUser = JSON.parseObject(userId, WmUser.class);
            WmThreadLocalUtils.setUser(wmUser);
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }
}
